package com.glsc.ngateway.opmanage.service.deposit;

import com.glsc.ngateway.common.api.common.utils.PageUtil;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryDayStartTrial;
import com.glsc.ngateway.common.base.domain.mysql.opmanagemain.deposit.DepositoryDaySummary;
import com.glsc.ngateway.common.base.repo.mysql.opmanagemain.deposit.DepositoryDaySummaryRepository;
import com.glsc.ngateway.opmanage.dto.DepositoryDayStartTrialDto;
import com.glsc.ngateway.opmanage.utils.DateUtils;
import com.glsc.ngateway.opmanage.utils.SpecificationUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;

@Service
public class DepositoryDaySummaryService {

    @Resource
    private DepositoryDaySummaryRepository depositoryDaySummaryRepository;

    @Resource
    private FsFundCarryInstService fsFundCarryInstService;

    /**
     * 创建当日保证金每日试算日初汇总数据
     *
     * @return
     */
    @Transactional
    public DepositoryDaySummary create(List<DepositoryDayStartTrial> resList) {
        DepositoryDaySummary summary = findByDate(DateUtils.getNowDateString());
        if (Objects.isNull(summary)) {
            summary = DepositoryDaySummary.builder().adjustInTotal(BigDecimal.ZERO).adjustOutTotal(BigDecimal.ZERO).paymentTotal(BigDecimal.ZERO).receiveTotal(BigDecimal.ZERO).foundationTotal(BigDecimal.ZERO).paddingAmount(BigDecimal.ZERO).effectDate(DateUtils.getNowDateString()).deleted("N").build();
        }

        //调出合计
        BigDecimal adjustOutTotal = BigDecimal.ZERO;
        //调入合计
        BigDecimal adjustInTotal = BigDecimal.ZERO;

        //计算当日保证金每日试算日初汇总数据
        if (CollectionUtils.isNotEmpty(resList)) {
            for (DepositoryDayStartTrial trial : resList) {
                if (Objects.nonNull(trial.getAdjustValue())) {
                    if (trial.getAdjustValue().compareTo(BigDecimal.ZERO) > 0) {
                        adjustInTotal = adjustInTotal.add(trial.getAdjustValue());
                    } else if (trial.getAdjustValue().compareTo(BigDecimal.ZERO) < 0) {
                        adjustOutTotal = adjustOutTotal.add(trial.getAdjustValue());
                    }
                }
            }
        }

        summary.setAdjustInTotal(adjustInTotal);
        summary.setAdjustOutTotal(adjustOutTotal);

        BigDecimal paymentTotal = fsFundCarryInstService.paymentTotal("32001618636050003568", Long.parseLong(DateUtils.getNowDateString().replaceAll("-", "")));
        BigDecimal recTotal = fsFundCarryInstService.recTotal("32001618636050003568", Long.parseLong(DateUtils.getNowDateString().replaceAll("-", "")));
        summary.setPaymentTotal(paymentTotal);
        summary.setReceiveTotal(recTotal);

        //基金暂不处理
        if (Objects.isNull(summary.getFoundationTotal())) {
            summary.setFoundationTotal(BigDecimal.ZERO);
        }

        //轧差金额=净收款-调入行合计-净付款-基金-调出行合计
        summary.setPaddingAmount(summary.getReceiveTotal().subtract(summary.getAdjustOutTotal()).subtract(summary.getAdjustInTotal()).subtract(summary.getPaymentTotal()).subtract(summary.getFoundationTotal()));

        depositoryDaySummaryRepository.save(summary);
        return summary;
    }


    /**
     * 保存基金信息并且触发从新试算
     *
     * @param dto
     * @return
     */
    public DepositoryDaySummary saveFoundationTotal(DepositoryDayStartTrialDto dto) {

        if (Objects.isNull(dto.getFoundationTotal())) {
            return null;
        }

        DepositoryDaySummary summary = findByDate(DateUtils.getNowDateString());
        if (Objects.isNull(summary)) {
            summary = DepositoryDaySummary.builder().adjustInTotal(BigDecimal.ZERO).adjustOutTotal(BigDecimal.ZERO).paymentTotal(BigDecimal.ZERO).receiveTotal(BigDecimal.ZERO).foundationTotal(BigDecimal.ZERO).paddingAmount(BigDecimal.ZERO).effectDate(DateUtils.getNowDateString()).deleted("N").build();
        }

        summary.setFoundationTotal(dto.getFoundationTotal());

        summary.setPaddingAmount(summary.getReceiveTotal().add(summary.getAdjustOutTotal()).subtract(summary.getAdjustInTotal()).subtract(summary.getPaymentTotal()).subtract(summary.getFoundationTotal()));
        depositoryDaySummaryRepository.save(summary);
        return summary;
    }

    /**
     * 根据时间查找保证金测算日初汇总数据
     *
     * @param date
     * @return
     */
    public DepositoryDaySummary findByDate(String date) {
        DepositoryDaySummary condition = DepositoryDaySummary.builder().effectDate(DateUtils.getNowDateString()).build();
        List<DepositoryDaySummary> summaries = depositoryDaySummaryRepository.findAll(Example.of(condition));
        if (CollectionUtils.isEmpty(summaries)) {
            return null;
        }
        return summaries.get(0);
    }


    /**
     * 分页查找
     *
     * @param pageNo
     * @param pageSize
     * @param param
     * @return
     */
    public Page<DepositoryDaySummary> page(int pageNo, int pageSize, Map<String, Object> param) {
        Sort.Direction direction = Sort.Direction.DESC;
        String sort = "createTime";

        pageNo = PageUtil.initPageNo(pageNo);
        pageSize = PageUtil.initPageSize(pageSize);

        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, direction, sort);
        Page<DepositoryDaySummary> page = depositoryDaySummaryRepository.findAll(SpecificationUtil.buildSpecification(param, DepositoryDaySummary.class), pageable);

        return page;
    }

    /**
     * 查询所有生效状态的保证金试算日初汇总数据
     *
     * @return
     */
    public List<DepositoryDaySummary> listAll() {
        List<DepositoryDaySummary> list = depositoryDaySummaryRepository.findAll(Example.of(DepositoryDaySummary.builder().deleted("N").build()));
        return list;
    }


    /**
     * 根据id查找
     *
     * @param id
     * @return
     */
    public DepositoryDaySummary findById(Integer id) {
        Optional<DepositoryDaySummary> optional = depositoryDaySummaryRepository.findById(id);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * 保存
     *
     * @param obj
     * @return
     */
    public DepositoryDaySummary save(DepositoryDaySummary obj) {
        return depositoryDaySummaryRepository.save(obj);
    }

    /**
     * 根据id删除
     *
     * @param id
     */
    public void delete(Integer id) {
        depositoryDaySummaryRepository.deleteById(id);
    }


}
